package com.etc.controller;


import com.etc.entity.Hospital;
import com.etc.entity.Message;
import com.etc.entity.Role;
import com.etc.entity.User;
import com.etc.service.HospitalService;
import com.etc.service.ShiorService;
import com.etc.util.MsgSend;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class loginController {
    Logger logger = Logger.getLogger(loginController.class);
    @Autowired
    @Qualifier(value = "shior")
    ShiorService shiorService;
    private String salt="abc";
    private String error=null;
    private MsgSend util=MsgSend.getUtil();
    @Autowired
    private HospitalService hospitalService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String Login(User user, HttpSession session, Model model, HttpServletRequest request, HttpServletResponse response,Integer remember){

        if(user.getUsername()==null){
            model.addAttribute("message", "账号不为空");
            error="登陆账号为空";
            logger.info(error);
            return "login";
        }
        String passone=user.getPassword();


        //主体,当前状态为没有认证的状态“未认证”
        Subject subject = SecurityUtils.getSubject();
        // 登录后存放进shiro token
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
        User u;Cookie cookie=null;Cookie cookie1=null;Cookie cookie2=null;
        System.out.println(remember);
        if(remember!=null){
           cookie=new Cookie("username",user.getUsername());
           cookie1=new Cookie("password",passone);
           cookie2=new Cookie("remember","1");
           cookie.setMaxAge(60*60*60);cookie.setPath("/");response.addCookie(cookie);
            cookie1.setMaxAge(60*60*60);cookie1.setPath("/");response.addCookie(cookie1);
            cookie2.setMaxAge(60*60*60);cookie2.setPath("/");response.addCookie(cookie2);
            logger.info("创建cookie");
        }else{
            if(request.getCookies()!=null){
             for(Cookie c:request.getCookies()){
              if(c.getName().equals("username")||c.getName().equals("password")||c.getName().equals("remember"))   {
               c.setPath("/");
                  c.setMaxAge(0);
                  response.addCookie(c);
                  logger.info("删除cookie"+c.getName());
              }
             }
            }
        }
        user = (User)shiorService.FindPasswordByname(user.getUsername());
        if(user==null){
            return "login";
        }

        //登录方法（认证是否通过）
        //使用subject调用securityManager,安全管理器调用Realm
        try {
            //利用异常操作
            //需要开始调用到Realm中
            System.out.println("========================================");
            System.out.println("1、进入认证方法");
            subject.login(token);
            logger.info("token认证出来");
            logger.info(user+"存入session的user信息");
            //存入用户信息
            session.setAttribute("user",user);
            //可通过subject或者user获取对象
            session.setAttribute("subject",subject);
        } catch (UnknownAccountException e) {
            System.out.println("铺货异常");
            logger.info("登录验证失败");
            model.addAttribute("error", "账号密码不正确");
            return "login";
        }
        if(user.getRoleid().getRolename().equals("admin")){
            return "redirect:/user/managerlist";
        }
        List<Hospital> list = hospitalService.queryByArea(1);
        model.addAttribute("list",list);
        logger.info("用户名为"+user.getUsername()+"登陆成功");
        return "redirect:/user/index";
    }

    //返回登录页面
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        logger.info("返回登录页面");
        return "login";
    }
      //手机验证码验证
    @ResponseBody
    @RequestMapping(value = "/code",method = RequestMethod.POST)
    public Message Loginpho(@RequestBody Message message, HttpSession session, Model model, HttpServletRequest request, HttpServletResponse response, Integer remember){
        try {
//            util.sendSms(message)
         if(util.sendSms(message)){
            logger.info("发送成功");
            message.setFlag("true");}
         else{
             model.addAttribute("error","发送错误，请确认手机号");
             logger.info("发送失败");
             message.setFlag("false");
         }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("发送失败");
            message.setFlag("false");
        }
        return message;
    }

    //手机登录
    @RequestMapping(value = "/login",method = RequestMethod.PUT)
    public String Loginphone(Message message, HttpSession session, Model model, HttpServletRequest request, HttpServletResponse response,Integer remember){

          String phone=message.getPhonenum();
          //根据手机号码查询对象
        User user=shiorService.FindPasswordByphone(phone);
        if(user==null){
            model.addAttribute("error","手机用户不存在");
            return "login";
        }
        //主体,当前状态为没有认证的状态“未认证”
        Subject subject = SecurityUtils.getSubject();
        // 登录后存放进shiro token
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
        //登录方法（认证是否通过）
        //使用subject调用securityManager,安全管理器调用Realm
        try {
            //利用异常操作
            //需要开始调用到Realm中
            System.out.println("========================================");
            System.out.println("1、进入认证方法");
            subject.login(token);
            user = (User)shiorService.FindPasswordByname(user.getUsername());
            logger.info(user+"存入session的user信息");
            //存入用户信息
            session.setAttribute("user",user);
            //可通过subject或者user获取对象
            session.setAttribute("subject",subject);
        } catch (UnknownAccountException e) {
            System.out.println("铺货异常");
            logger.info("登录验证失败");
            model.addAttribute("error", "手机验证失败");
            return "login";
        }
        List<Hospital> list = hospitalService.queryByArea(1);
        model.addAttribute("list",list);
        logger.info("用户名为"+user.getUsername()+"登陆成功");
        return "redirect:/user/index";
    }






    //没权限时候返回页面
    @ResponseBody
    @RequestMapping("/nopermission")
    public String noPermission(){
        logger.info("没有权限");
        return "error";
    }
    //登入
    @RequestMapping(value = "/index")
    public String index(HttpSession session,Model model) {
        List<Hospital> list = hospitalService.queryByArea(1);
        model.addAttribute("list",list);
        return "index";
    }

    //登入管理员
    @RequestMapping(value = "/managerlist")
    public String indexs(HttpSession session) {
        return "Left";
    }

    //登出
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        session.removeAttribute("subject");
        return "redirect:/user/login";
    }


    @RequestMapping(value = "/map",method = RequestMethod.GET)
    public String map(Model model){

        logger.info("登陆地图");
        return "china";
    }



    @RequestMapping("/check")
    public String check(HttpSession session){

        Subject subject=(Subject)session.getAttribute("subject");

        User user=(User)subject.getPrincipal();
        System.out.println(user.toString()+"用户信息");
        return "permission";
    }

    @RequestMapping("/checks")
    public String checks(HttpSession session){
        System.out.println("进入checks");
        return "permission";
    }


    @RequestMapping(value = "register",method = RequestMethod.POST)
    public String register(User user){
        Role role = new Role();role.setRoleid(3);user.setRoleid(role);
        user.setPassword(new Md5Hash(user.getPassword(), salt).toHex());
        shiorService.register(user);
        logger.info(user.getUsername()+"注册成功");
        return "redirect:/user/login";
    }

    @RequestMapping("/loginbyphone")
    public String phonelogin(HttpSession session){
        return "phonelogin";
    }

    @ResponseBody
    @RequestMapping("/vip")
    public String vip(HttpSession session){
        System.out.println("进入vip");
        return "vip";
    }



    @RequestMapping("/readName")
    public String readName(HttpSession session){

        return "name";
    }

    @RequestMapping("/readData")
    public String readData(){

        return "data";
    }

    @RequestMapping("/student")
    public String readData2(){

        return "student";
    }


    @RequestMapping("/teacher")
    public String readData1(){

        return "teacher";
    }



}
